import axios from "axios";
import { useState } from "react";
import { Notify } from 'react-vant'
export interface ListState {
  "id": string,
  "title": string,
  "images": string[],
  "price": number,
  "sellCount": number,
  "desc": string,
}

export function useFetchLists() {
  // 1. 容器
  const [lists, setData] = useState<ListState[]>([])
  const [pageCode, setPageCode] = useState(1)
  const [finished, setFinished] = useState(false)
  // 2. 请求
  const fetchLists = async () => {
    const resp = await axios.get('/api/lists', { params: { pageCode } });
    const { code, data, message } = resp.data;
    if(code === 200) {
      setData([...lists, ...data])
      setPageCode(pageCode + 1)
    } else if(code === 400) {
      Notify.show({ type: 'danger', message })
    } else if(code === 201) {
      Notify.show({ type: 'danger', message })
      setFinished(true)
    }
  
  }
  // 4. 返回
  return {
    lists,
    fetchLists,
    finished
  }
}